package com.chao.stucture.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author : Rookie
 * @description : 翻转二叉树
 * @date : 2023/6/18
 */
public class InvertTree {

    public static void main(String[] args) {
        int[] input = {1, 2, 3, -1, 5, -1, 4};
        TreeNode root = BinaryTreeUtil.buildTree(input);
        System.out.println("翻转前");
        BinaryTreeUtil.Traversal.sequenceTraversal(root);
        TreeNode treeNode = cycleImpl(root);
        System.out.println("\n翻转后");
        BinaryTreeUtil.Traversal.sequenceTraversal(treeNode);
    }

    private static TreeNode cycleImpl(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();
            swapChildren(curr);
            if (curr.left != null) {
                queue.offer(curr.left);
            }
            if (curr.right != null) {
                queue.offer(curr.right);
            }
        }
        return root;
    }

    private static TreeNode recursiveImpl(TreeNode root) {
        if (root == null) {
            return null;
        }
        swapChildren(root);
        recursiveImpl(root.left);
        recursiveImpl(root.right);
        return root;
    }

    private static void swapChildren(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }

}
